package edu.chinasoft.servlet;

import edu.chinasoft.domain.Function;
import edu.chinasoft.domain.User;
import edu.chinasoft.service.FunctionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "ServletForFunctionByUser",value = "/servlet/servletforfunctionbyuser")
public class ServletForFunctionByUser extends HttpServlet {
    private Logger logger = LoggerFactory.getLogger(ServletForFunctionByUser.class);
    private FunctionService functionService;


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        logger.debug("ServletForFunctionByUser>>>doGet start ……");
        //禁止使用缓存

        response.setDateHeader("Expires", 0);
        response.setHeader("pragma", "no-cache");
        response.setHeader("cache-control", "no-cache");


        //获取当前用户
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute("user");

        if(user==null){
            request.getRequestDispatcher("/left.jsp?key="+System.currentTimeMillis()).forward(request, response);
            return;
        }





        //调用服务层方法，获取关于当前用户的权限
        //初始化servelt里关于服务层方法成员变量
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        functionService = wac.getBean("functionService", FunctionService.class);

        List<Function> functionList = functionService.getFunctionByUser(user);


        //把权限保存到session中
        session.setAttribute("allfunction", functionList);


        //禁止客户端使用缓存
        request.getRequestDispatcher("/left.jsp?key="+System.currentTimeMillis()).forward(request, response);

        logger.debug("ServletForFunctionByUser>>>doGet end ……");
    }
}
